<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i>后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/sys-admin/permission/admin' }">管理员管理</el-breadcrumb-item>
      <el-breadcrumb-item>{{$router.currentRoute.name}}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>

    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password"></el-input>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="ruleForm.nickname"></el-input>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="ruleForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="邮箱邮箱" prop="email">
        <el-input v-model="ruleForm.email"></el-input>
      </el-form-item>
      <el-form-item label="简介" prop="description">
        <el-input v-model="ruleForm.description"></el-input>
      </el-form-item>
      <el-form-item label="是否启用" prop="enable">
        <el-switch
            v-model="ruleForm.enable"
            active-color="#13ce66"
            inactive-color="#ccc"
            active-value="1"
            inactive-value="0">
        </el-switch>
      </el-form-item>

      <el-form-item label="角色" prop="roleIds">
        <el-select v-model="ruleForm.roleIds" multiple placeholder="请选择">
          <el-option
              v-for="item in roleListOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="头像" prop="avatar">
        <div class="picture-list">
          <el-upload
              name="imageFile"
              class="picture-uploader"
              :action="uploadAvatar"
              :show-file-list="false"
              :on-success="handleUploadSuccess">
            <i class="el-icon-upload picture-uploader-icon"></i>
            <div class="picture-uploader-text">仅允许上传 <i>JPG</i> / <i>PNG</i> 格式的图片</div>
            <div class="picture-uploader-text">仅允许上传不超过 <i>1MB</i> 的图片</div>
          </el-upload>
          <div class="picture-item" v-show="ruleForm.avatar != ''">
            <el-image class="image"
                      :src="ruleForm.avatar" fit="cover"></el-image>
          </div>
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">添加</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
        <el-button type="warning" @click="$router.push('./')">返回管理员列表</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>


<script>
import global from '../../../Global'
let preAdminUrl = global.preAdmins ;
let preRoleUrl = global.preRoles ;
let preResourceUrl = global.preResources ;
let queryAll = global.queryAll ;
export default {
  data() {
    return {
      uploadAvatar: preResourceUrl+'/upload/image/avatar',
      roleListOptions: [],
      ruleForm: {
        username: '',
        password: '123456',
        nickname: '',
        avatar: '',
        phone: '11234567890',
        email: '222@qq.com',
        enable: '1',
        roleIds: ''
      },
      rules: {
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 25, message: '长度在 2 到 25 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[0-9]{10}$/, message: '手机号码格式错误', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/, message: '邮箱格式错误', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入简介', trigger: 'blur' }
        ],
        roleIds: [
          { required: true, message: '请选择角色', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    //新增
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = preAdminUrl + "/add-new";
          let formData =this.qs.stringify(this.ruleForm);

          let localJwt = localStorage.getItem('localJwt');
          this.axios.create({'headers': {'Authorization': localJwt}})
              .post(url, formData).then((response) => {
            let jsonResult = response.data;
            if(jsonResult.state == 20000){
              this.$notify.success({title: '成功',
                message: '添加成功'
              });

              this.resetForm(formName);
            }else {
              this.$alert(jsonResult.message, '错误', {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //头像上传成功
    handleUploadSuccess(response){
      this.ruleForm.oldUrl =  this.ruleForm.avatar;
      this.ruleForm.avatar = response.data.url;
      this.handleDeletePicture();
    },
    //物理删除服务器保存头像
    handleDeletePicture(){
      if(this.ruleForm.oldUrl == ''){
        return;
      }
      let url = preResourceUrl + "/remove/image/avatar";
      let formData = this.qs.stringify(this.ruleForm);

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url, formData).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          console.log("图片物理删除成功!");
        }else{
          console.log("图片物理删除失败!");
        }
      });
    },
    //加载角色全列表
    loadRoleList(){
      let url = preRoleUrl+queryAll;

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          console.log("jsonResult", jsonResult)
          this.roleListOptions = jsonResult.data.list;
        }else if(jsonResult.state == 40100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              localStorage.removeItem("localJwt");
              this.$router.push("/login");
            }
          });
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  mounted() {
    this.loadRoleList();
  }
}
</script>
